<template>
  <div class="NoticeBar">
    <template v-for="(item, index) in list">
      <transition name="slide" :key="index" @after-enter="afterEnter">
        <span v-if="index == cur">{{ item[prop] }}</span>
      </transition>
    </template>
  </div>
</template>
<script>
export default {
  name: "NoticeBar",
  props: {
    list: {
      type: Array,
      default() {
        return [];
      }
    },
    prop: {
      type: String,
      default: "title"
    },
    dealy: {
      type: Number,
      default: 3000
    }
  },
  data() {
    return {
      cur: -1,
      timer: null
    };
  },
  mounted() {
    this.cur = 0;
  },
  methods: {
    afterEnter(el) {
      if (this.list.length == 0) {
        return false;
      }
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.cur++;
        if (this.cur >= this.list.length) {
          this.cur = 0;
        }
      }, this.dealy);
    }
  },
  destroyed() {
    clearTimeout(this.timer);
  }
};
</script>
<style lang="less" scoped>
.NoticeBar {
  position: relative;
  top: 0;
  left: 0;
  width: 100%;
  overflow: hidden;
  height: 100%;
  span {
    left: 0;
    top: 0;
    position: absolute;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100%;
    font-size: 12px;
    display: flex;
    align-items: center;
  }
  .slide-enter-active,
  .slide-leave-active {
    // 启用硬件加速
    will-change: transform;
    transition: all 1s;
    height: 100%;
    left: 0;
    top: 0;
    position: absolute;
    backface-visibility: hidden;
  }
  .slide-enter {
    opacity: 0;
    transform: translate3d(0, 100%, 0);
  }

  .slide-leave-active {
    opacity: 0;
    transform: translate3d(0, -100%, 0);
  }
}
</style>
